package com.example.nettydemo.codec.ptotobuf;

import com.alibaba.fastjson.JSON;
import com.google.protobuf.InvalidProtocolBufferException;

import java.util.ArrayList;
import java.util.List;

public class TestSubscibeReqProto {

    private static byte[] encode(SubscibeReqProto.SubscibeReq req){
        return req.toByteArray();
    }

    private static SubscibeReqProto.SubscibeReq decode(byte[] body) throws InvalidProtocolBufferException {
        return SubscibeReqProto.SubscibeReq.parseFrom(body);
    }

    private static SubscibeReqProto.SubscibeReq createSubscibeReq(){
        SubscibeReqProto.SubscibeReq.Builder builder = SubscibeReqProto.SubscibeReq.newBuilder();
        builder.setSubReqID(1);
        builder.setUserName("name1");
        builder.setProductName("book1");

        List<String> address =  new ArrayList<>();
        address.add("地址1");
        address.add("地址2");
        builder.addAllAddress(address);

        return builder.build();
    }

    public static void main(String[] args) throws InvalidProtocolBufferException {
        SubscibeReqProto.SubscibeReq req = createSubscibeReq();
        System.out.println("编码前: " + req.toString());
        SubscibeReqProto.SubscibeReq req2 = decode(encode(req));
        System.out.println("编码后: " + req2.toString());
        System.out.println("结果: " + req.equals(req2));

        // 编码后的长度: 34
        System.out.println("编码后的长度: " + encode(req).length);

        SubscibeReq req1 = new SubscibeReq();
        req1.setSubReqID(1);
        req1.setUserName("name1");
        req1.setProductName("book1");
        List<String> address =  new ArrayList<>();
        address.add("地址1");
        address.add("地址2");
        req1.setAddress(address);

        // 编码后的长度2: 87
        System.out.println("编码后的长度2: " + JSON.toJSONString(req1).getBytes().length);
    }
}
